<?php

// +----------------------------------------------------------------------
// | 作品展示
// +----------------------------------------------------------------------

namespace Home\Controller;
use Common\Controller\Base;
use Think\Controller;
use Think\Model;

class WorksController extends Base {

    private $userid, $username;

    //初始化
    protected function _initialize() {
        parent::_initialize();
        $this->userid = service("Passport")->userid;
        $this->username = service("Passport")->usename;
    }

    /**
     * 作品详情展示
     */
    public function detail(){
        $workid=I('get.workid');
        if(empty($workid)){
            $this->error('您访问的页面不存在');
        }
        //增加点击数
        M('Works')->where(array('workid'=>$workid))->setInc('clicknum');
        $detail=D('Works')->relation(true)->find($workid);
        if(!$detail){
            $this->error('您访问的作品不存在');
        }
      
        //start yf
        $yf_thumb = array();
        $yf_pic = array();
        if(!empty($detail['all_pic']))
        {
        	$yf_arr = json_decode($detail['all_pic'], true);
        	$yf_temp = array();
        	foreach($yf_arr as $k => $v)
        	{
        		$yf_thumb[] = $v;
        		$yf_ex = explode("/", $v);
        		$yf_ex[count($yf_ex)-1] = str_replace("yf_", "", $yf_ex[count($yf_ex)-1]);
        		$yf_pic[] = implode("/", $yf_ex);
        	}
        }
        else
        {
        	$yf_arr = array();
        	$yf_thumb[] = $yf_pic[] = $detail['image'];
        }
        $detail['pic_num'] = count($yf_thumb);
        $detail['thumb'] = implode(",", $yf_thumb);
        $detail['pic'] = implode(",", $yf_pic);
        $detail['WorksMaterials_count'] = count($detail['WorksMaterials']);
        $detail['title'] = trim($detail['title']);
        //end
       
        $this->assign('data',$detail);
        //点赞总数
        $this->digallnum=$detail['goodnum']+$detail['badnum'];

        //综合评价
        if($detail['goodnum']==0 && $detail['badnum']==0){
            $dig['digavg']=0;
            $dig['goodprecent']=50;
            $dig['badprecent']=50;
        }else{
            $digavg=round(($detail['goodnum']/($detail['goodnum']+$detail['badnum'])),2);
            $dig['digavg']=$digavg*10;
            $dig['goodprecent']=$digavg*100;
            $dig['badprecent']=(1-$digavg)*100;
        }
        $this->dig=$dig;

        //点赞判断
        $this->digtype=M('Dig')->field('digtype,id')->where(array('userid'=>$this->userid,'status'=>true,'infoid'=>$workid))->find();
        //收藏判断
        $this->favoritenum=getCount('UserFavorite',array('userid'=>$this->userid,'status'=>true,'infoid'=>$workid));

        //右侧广告
        $this->rightad=parent::getAdvert(8,3,0,2);

        //点赞人员列表
        $diguser=new Model();
        $diguerlist=$diguser->table(array(
            C('DB_PREFIX').'dig'=>'D',
            C('DB_PREFIX').'user'=>'U',
          ))->where('D.userid=U.userid and D.status=true and D.digtype=1 and D.infoid='.$workid.'')
            ->field('U.uavatar,U.openuid')
            ->limit(10)
            ->select();
        $this->assign('diglist',$diguerlist);

        //评论
        $where['infoid']=$workid;
        $where['type']=1;
        $where['parent_id'] = 0;
        $count = M('UserMessage')->where($where)->count();
       // $limitRows = 5; // 设置每页记录数
        $limitRows = C('YF_PAGE');
        $page = $this->ajaxpage($count,$limitRows,'#msg','ajax_div','ajax_page_div');

        $Model=new Model();
        $message=$Model
            ->table(array(
                    C('DB_PREFIX').'user_message'=>'M',
                    C('DB_PREFIX').'user'=>'U',
                )
            )
            ->where('M.userid=U.userid and M.status=true and M.infoid='.$workid.' and M.type=1 and M.parent_id=0')//yf 0912
            ->field('M.create_time,M.content,U.nickname,U.uavatar,U.openuid,U.uprovince,U.ucity,U.userid,M.id,M.touserid,U.ifrz')
            ->order('M.create_time DESC')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();
        
        foreach($message as $k=>$v){
        	$child_temp = array();
        	$child_temp = $Model->table(C('DB_PREFIX').'user_message')->field('*')->where(array('parent_id' => $v['id']))->order('create_time ASC')->select();
        
        	$message[$k]['childlist'] = array();
        	if($child_temp)
        	{
        		foreach($child_temp as $yk => $yv)
        		{
        			if($yv['userid'] == 0)
        			{
        				$child_temp[$yk]['nickname'] = "烘焙圈";
        				$child_temp[$yk]['openuid'] = 0;
        			}
        			else 
        			{
        				$yf_user = array();
        				$yf_user = M('User')->field('openuid, nickname, uprovince, ucity, uavatar, ifrz')->where(array('userid'=>$yv['userid']))->find();
        				$child_temp[$yk]['nickname'] = $yf_user['nickname'];
        				$child_temp[$yk]['openuid'] = $yf_user['openuid'];
        				$child_temp[$yk]['uprovince'] = $yf_user['uprovince'];
        				$child_temp[$yk]['ucity'] = $yf_user['ucity'];
        				$child_temp[$yk]['uavatar'] = $yf_user['uavatar'];
        				$child_temp[$yk]['ifrz'] = $yf_user['ifrz'];
        			}
        			if($yv['touserid'] != 0)
        			{
        				$child_temp[$yk]['touser'] = M('User')->field('openuid,nickname')->where(array('userid'=>$yv['touserid']))->find();
        			}
        			else
        			{
        				$child_temp[$yk]['touser']['nickname'] = "烘焙圈";
        				$child_temp[$yk]['touser']['openuid'] = 0;
        			}
         		}
        		$message[$k]['childlist'] = $child_temp;
        	}
        	$message[$k]['tempname'] = hy_substr($v['nickname'], 4, true); 
        	//$message[$k]['tempname'] = $v['nickname'];
        	$message[$k]['touser'] = array();
        	if(!empty($v['touserid']))
        	{
            	$message[$k]['touser']=M('User')->field('openuid,nickname')->where(array('userid'=>$v['touserid']))->find();
        	}
        }
       unset($where['parent_id']);
        $this->msgcount=M('UserMessage')->where($where)->count();
        $this->msgtype=1;
        $this->assign('msglist',$message);
        $this->assign('page',$page->show());

        if(IS_AJAX){
            exit($this->fetch('msglist'));
        }

        //参照做出的作品

         $copylist=$Model
             ->table(array(
                 C('DB_PREFIX').'works'=>'W',
                 C('DB_PREFIX').'user'=>'U',
            ))
             ->where('W.userid=U.userid and W.status=true and W.type=2 and W.copyid='.$workid)
             ->field('U.openuid,U.nickname,U.uavatar,W.title,W.image,W.workid,W.create_time,W.title')
             ->order('W.workid DESC')
             ->limit(4)
             ->select();
        $this->copylist=$copylist;

        //十大热门配方
        $rmdatse = M('Works')->where('type=1')->order('clicknum DESC')->limit(10)->select();
        
        $this->assign('rmdatse', $rmdatse);

        $this->display();
    }


    /**
     * 留言
     */
    public function sendmsg(){
        $post=I('post.');
        $post['userid']=$this->userid;
        $this->check();
        if($post['workuid']==$post['userid']){
            $this->error('您不能给自己留言!');
        }
        if(D('Home/Commons')->sendMessage($post,1)){
            $this->success('感谢您的留言!');
        }else{
            $error = D('Home/Commons')->getError();
            $this->error($error ? $error : '留言失败,请稍候再试！');
        }
    }

    /**
     * 点赞
     */
    public function adddig(){
        $get=I('get.');
        $get['userid']=$this->userid;
        $this->check();
        $workuid=M('Works')->where(array('workid'=>$get['infoid']))->getField('userid');
        if($workuid==$this->userid){
            $this->error('您不能给自己的作品点赞!');
        }
        if(D('Home/Commons')->adddig($get,1)){
            if($get['digtype']==1){
                $this->success('感谢您的鼓励,我们会再接再厉!');
            }elseif($get['digtype']==0){
                $this->success('感谢您的评价,我们会继续努力!');
            }
        }else{
            $error = D('Home/Commons')->getError();
            $this->error($error ? $error : '点赞失败,请稍候再试！');
        }
    }

    /**
     * 取消点赞
     */
    public function canceldig(){
        $digModel=M('Dig');
        $get=I('get.');
        $this->check();
        $where['userid']=$this->userid;
        $where['infoid']=$get['infoid'];
        $data['status']=false;
        $digtype=$digModel->where(array('userid'=>$this->userid,'infoid'=>$get['infoid']))->getField('digtype');

        $result=$digModel->where($where)->save($data);
        if($result){
            if($digtype==1){
                M('Works')->where(array('workid'=>$get['infoid']))->setDec('goodnum',1);
            }elseif($digtype==0){
                M('Works')->where(array('workid'=>$get['infoid']))->setDec('badnum',1);
            }
            $this->success('成功取消您对本作品的点赞!');
        }else{
            $this->error('取消操作失败');
        }
    }


    /**
     * 收藏作品操作
     */
    public function addfavorite(){
        $get=I('get.');
        $get['userid']=$this->userid;
        $this->check();
        $workuid=M('Works')->where(array('workid'=>$get['infoid']))->getField('userid');
        if($workuid==$this->userid){
            $this->error('您不能收藏自己的作品!');
        }
        if(D('Home/Commons')->addfavorite($get,1)){
            $this->success('该作品已成功添加到您的收藏夹!');
        }else{
            $error = D('Home/Commons')->getError();
            $this->error($error ? $error : '收藏失败,请稍候再试！');
        }
    }

    /**
     * 取消收藏操作
     */
    public function cancelfavorite(){
        $this->check();
        $digModel=M('UserFavorite');
        $get=I('get.');
        $where['userid']=$this->userid;
        $where['infoid']=$get['infoid'];
        $data['status']=false;
        $result=$digModel->where($where)->save($data);
        if($result){
            M('Works')->where(array('workid'=>$get['infoid']))->setDec('favoritenum',1);
            $this->success('成功取消您对本作品的收藏!');
        }else{
            $this->error('取消操作失败');
        }
    }

    /**
     * 测试表单验证之用
     */

    public function test(){
        $this->display();
    }

    public function validate(){
        $this->display();
    }

    public function tests(){
        $post=I('post.');
        exit(json_encode(array('info'=>$post['title'],'status'=>true)));
    }


    //



}